#!/usr/bin/env python3
import os
import hlna
import time
import unittest
import zipfile
from click.testing import CliRunner
from pathlib import Path
home_dir = Path.home()
config_hlna = f"{home_dir}/.config/hlna/"

from unittest.mock import patch, MagicMock

from hlna import config


class TestConfig(unittest.TestCase):

    @patch('builtins.input', side_effect=['1'])
    @patch('hlna.config_ark')
    def test_config_ark_valid(self, config_ark_mock, input_mock):
        config()
        config_ark_mock.assert_called_once()

    @patch('builtins.input', side_effect=['2'])
    @patch('hlna.config_7daystodie')
    def test_config_7daystodie_valid(self, config_7daystodie_mock, input_mock):
        config()
        config_7daystodie_mock.assert_called_once()

    @patch('builtins.input', side_effect=['3'])
    @patch('sys.stdout', new_callable=MagicMock)
    def test_config_invalid_game(self, mocked_stdout, input_mock):
        config()
        self.assertEqual(mocked_stdout.getvalue().strip(), "Пока есть только ARK и 7Days xD")

    @patch('builtins.input', side_effect=['a', '1'])
    @patch('hlna.config_ark')
    @patch('sys.stdout', new_callable=MagicMock)
    def test_config_invalid_input(self, mocked_stdout, config_ark_mock, input_mock):
        config()
        config_ark_mock.assert_called_once()
        self.assertEqual(mocked_stdout.getvalue().strip(),
                         "Выберите игру для конфигурирования\n1. ARK Survival Evolved\n2. 7 Days to Die\n: ")
class TestFindFile(unittest.TestCase):
    def setUp(self):
        self.test_dir = 'test_dir'
        os.mkdir(self.test_dir)
        self.test_files = ['foo.conf', 'bar.ini', 'qux.cfg', 'baz.txt', '.directory']
        for f in self.test_files:
            open(os.path.join(self.test_dir, f), 'w').close()

    def tearDown(self):
        for f in self.test_files:
            os.remove(os.path.join(self.test_dir, f))
        os.rmdir(self.test_dir)

    def test_find_file(self):
        res = hlna.find_file(self.test_dir)
        self.assertEqual(sorted(res), sorted(['foo.conf', 'bar.ini', 'qux.cfg', 'baz.txt']))

    def test_find_file_empty_dir(self):
        res = hlna.find_file('empty_dir')
        self.assertEqual(res, [])

class TestCreateDir(unittest.TestCase):
    def test_create_dir(self):
        testdir = 'testdir'
        self.assertFalse(os.path.exists(testdir))
        hlna.create_dir(testdir)
        self.assertTrue(os.path.exists(testdir))
        os.rmdir(testdir)

class TestRestore(unittest.TestCase):

    def setUp(self):
        self.runner = CliRunner()
        self.zip_file_name = "test_backup.zip"
        os.system("touch test_file1.txt test_file2.txt")
        self.file_names = ["test_file1.txt", "test_file2.txt"]
        with zipfile.ZipFile(self.zip_file_name, 'w') as zip_file:
            for file_name in self.file_names:
                zip_file.write(file_name)

    def tearDown(self):
        os.remove(self.zip_file_name)
        for file_name in self.file_names:
            os.remove(file_name)

    def test_restore(self):
        result = self.runner.invoke(hlna.restore, ["test", "-d", self.zip_file_name])
        self.assertEqual(result.exit_code, 0)
        for file_name in self.file_names:
            self.assertTrue(os.path.exists("./"+file_name))

class TestBackup(unittest.TestCase):

    def setUp(self):
        data = hlna.read_yaml(g="path_server")
        if data['path_server'] == "":
            data['path_server'] = f"{home_dir}Servers/ARK/Backups/test_backup/"
        else:
            data['path_server'] = f"{data['path_server']}ARK/Backups/test_backup/"
        self.backup_path = data['path_server']
        self.runner = CliRunner()
        with open(f"{config_hlna}/ARK/test_file.txt", "w") as file:
            file.write("test content")

    def tearDown(self):
        os.remove(f"{config_hlna}ARK/test_file.txt")
        for root, dirs, files in os.walk(self.backup_path):
            for file in files:
                os.remove(os.path.join(root, file))
        os.rmdir(self.backup_path)

    def test_backup(self):
        result = self.runner.invoke(hlna.backup, ["ark_test"])
        self.assertEqual(result.exit_code, 0)
        self.assertTrue(os.path.exists(self.backup_path))

        target = f"{self.backup_path}ark_test_backup-" + time.strftime('%Y_%m_%d') + '.zip'
        self.assertTrue(os.path.exists(target))
        with zipfile.ZipFile(target, 'r') as zip_file:
            self.assertEqual(zip_file.testzip(), None)
        self.assertTrue(os.path.exists(os.path.join(target, f"{config_hlna}ARK/test_file.txt")))

class TestGetExternalIP(unittest.TestCase):
    def test_backup(self):
        self.assertTrue(bool(hlna.get_external_ip()))

#class TestGetExternalIP(unittest.TestCase):
#    def test_backup(self):
#        self.assertTrue(bool(hlna.get_external_ip()))
if __name__ == '__main__':
    unittest.main()


    



